﻿/********************************************************************************
** 作者： 易景安
** 创建时间： 2011-11-15
** 描述：
** 角色管理列表-涉及到的相关方法
********************************************************************************/

var isEdit = false;
var storeRole;     // 角色数据源
var gridRole;      // 角色Grid
var pageSize = 20; // 每页显示数
var winAddRole;    // 打开角色窗体
var winEditRole;   // 打开角色窗体
var RoleID = '';   // 角色ID
var roleForm; var roleDistributionWindow;
var RoleActionForm; var RoleActionWindow;
var fromStoreUser; var toStoreUser;

Ext.onReady(function() {
    Ext.QuickTips.init();

    // 本地加载图片代码
    Ext.BLANK_IMAGE_URL = strPath + 'extjs/resources/images/default/s.gif';

    // 选择人员列表
    var httpProxy = new Ext.data.HttpProxy({
        url: strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=GetFoothillRoleByPage'
    });
    // 人员的读取方式
    var readerProxy = new Ext.data.JsonReader({
        root: 'Records',
        totalProperty: 'totalCount',
        fields: [
                  { name: 'RoleID' },
                  { name: 'RoleName' },
                  { name: 'RoleDesc' }
             ]
    });
    // 定义人员数据源
    storeRole = new Ext.data.Store({
        proxy: httpProxy,
        reader: readerProxy,
        remoteSort: true
    });
    // 设置显示列的Title
    var ChooseView = new Ext.grid.GridView({ forceFit: true, sortAscText: '升序', sortDescText: '降序' });
    ChooseView.columnsText = '列显示/隐藏';
    // 加载前的事件,或窃取相关参数
    storeRole.on('beforeload', function() {
        var RoleName = Ext.get("txtChRoleName").dom.value;
        storeRole.baseParams = {
            RoleName: RoleName
        };
    });
    // 设置页脚的显示样式。
    var ChooseBar = new Ext.PagingToolbar({
        pageSize: pageSize,
        store: storeRole,
        beforePageText: '第',
        afterPageText: '页 共{0}页',
        firstText: '第一页',
        prevText: '前一页',
        nextText: '后一页',
        lastText: '最后一页',
        refreshText: '刷新',
        displayInfo: true,
        displayMsg: '显示第 {0} - {1} 条数据, 共 {2} 条数据',
        emptyMsg: "没有数据可以显示"
    });
    // grid的选择列
    var smRoleListModel = new Ext.grid.CheckboxSelectionModel({
        singleSelect: false,
        listeners: {
            rowselect: function(sm, row, rec) {
            }
        }
    });
    var GridToolBar = new Ext.Panel({
        labelAlign: 'top',
        frame: false,
        bodyStyle: 'border:0px;',
        width: "100%",
        html: '<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background:#BFEAFD;"><tr><td width="70" align="right" height="26">&nbsp;角色名称：</td><td align="left" style="width:310px;"><table border="0" cellspacing="0" cellpadding="0"><tr><td width="79" align="left"><input type="text" class="input_l95p_style" style="width: 280;" id="txtChRoleName"> </td></tr></table></td><td align="left"><input name="button" type="button" style="padding: 0px 5px; height: 22px;" id="btnSearchAll" onclick="doSearchRole(true);" value="查 询" /></td></tr><tr id="RoleManage"><td height="26" colspan="5" align="left"><table border="0" cellspacing="0" cellpadding="0"><tr><td width="28" height="20" align="center" id="divAddRoleInfoImg"><img src="images/ico_28.gif" width="16" height="16" /></td><td width="65" class="general_h1_gray_c01_font" id="divAddRoleInfo"><span style="cursor: hand;text-decoration:underline;" onclick="ShowRoleWin();">新增角色</span></td><td width="28" align="center" class="general_h1_gray_c01_font" id="divCancellationImg"><img src="images/ico_21.gif" width="16" height="16" /></td><td width="65" align="left" class="general_h1_gray_c01_font" id="divCancellation"><span style="cursor: hand;text-decoration:underline;" onclick="DelRole();">删除角色</span></td></tr></table></td></tr></table>'
    });
    // 角色Grid的定义
    gridRole = new Ext.grid.GridPanel({
        id: 'pagedef-grid',
        store: storeRole,
        renderTo: "leftPanel",
        cm: new Ext.grid.ColumnModel([
            smRoleListModel,
            { id: 'RoleID', header: "角色ID", sortable: false, dataIndex: 'RoleID', hidden: true },
            { header: "角色名称", sortable: true, dataIndex: 'RoleName', renderer: OpenRoleInfo },
            { header: "角色说明", sortable: true, dataIndex: 'RoleDesc' },
            { header: "角色用户分配", sortable: true, dataIndex: 'RoleID', renderer: OpenRoleUser },
            { header: "角色权限分配", sortable: true, dataIndex: 'RoleID', renderer: OpenRoleAcction }
        ]),
        sm: smRoleListModel,
        height: parent.Ext.get("ContentFrame").getHeight() - 25,
        bbar: ChooseBar,
        view: ChooseView,
        frame: false,
        border: false,
        loadMask: { msg: '正在加载数据，请稍侯... ...' },
        tbar: GridToolBar
    });

    gridRole.addListener('rowdblclick', function(gridObj, rowIdx, e) {
    });
    // 角色用户分配
    function OpenRoleUser(value, metadate, record, colIndex, rowIndex) {
        return "<a href=\"javascript:OpenRoleUserWin('" + record.get("RoleID") + "')\" title='角色用户分配'>分配用户</a>";
        // return "<a href=\"javascript:SetRoleUser('"+record.get("RoleID")+"')\" title='角色用户分配'>分配用户</a>";
    }
    // 角色功能分配
    function OpenRoleAcction(value, metadate, record, colIndex, rowIndex) {
        return "<a href=\"javascript:OpenResourceWin('" + record.get("RoleID") + "')\" title='角色权限分配'>分配权限</a>";
        // return "<a href=\"javascript:SetRoleAction('"+record.get("RoleID")+"')\" title='角色权限分配'>分配权限</a>";
    }
    // 查看角色
    function OpenRoleInfo(value, metadate, record, colIndex, rowIndex) {
        winOrganization.setTitle("编辑角色");
        return "<a href=\"javascript:GetRoleInfo('" + record.get("RoleID") + "')\" title='" + value + "'>" + value + "</a>";
    }
    // 新增角色
    winOrganization = new Ext.Window({
        title: '新增角色',
        width: 400,
        height: 202,
        autoScroll: true,
        bodyStyle: 'border-top:0;padding:2 2 2 2;background:#E5E2EE;',
        closeAction: 'hide',
        plain: true,
        modal: true,
        bodyStyle: 'padding:5px;',
        buttonAlign: 'center',
        contentEl: 'divRoleInfo',
        buttons: [{
            text: '确定',
            id: 'btnSerachInfo',
            name: 'btnSerachInfo',
            handler: function() {
                AddRole();
            }
        }, {
            text: '关闭',
            handler: function() {
                winOrganization.hide();
            }
        }
        ]
    });
    // 角色查询
    doSearchRole(true);
});

// 打开选择权限的窗体
function OpenResourceWin(RoleIDs) {
    // 提交
    var strUrl = strPath + 'GGFW/BaseInfo/FoothillMenuCommand.fwf?Method=GetFunctionsByRole';
    Ext.Ajax.request({
        url: strUrl,
        method: 'POST',
        params: {
            RoleID: RoleIDs
        },
        failure: function(response, options) {
            ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
        },
        success: function(response, options) {
            var json = response.responseText;
            var obj = parseJsonResult(json);

            if (obj == null || !obj.Success) {
                showMessage("错误！", "保存出现错误！请查看详细原因。", obj.Message);
            }
            else {
                var ids = "";
                for (var i = 0, len = obj.data.length; i < len; i++) {
                    if (i == 0)
                        ids = obj.data[i].MenuID + ',';
                    else
                        ids = ids + "," + obj.data[i].MenuID;
                }
                ShowRoleMenuWin(ids, RoleIDs, '角色权限分配');
            }
        }
    });
}
// 打开选择用户的窗体
function OpenRoleUserWin(RoleIDs) {
    // 提交
    var strUrl = strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=SearchRoleUsers';
    Ext.Ajax.request({
        url: strUrl,
        method: 'POST',
        params: {
            RoleID: RoleIDs
        },
        failure: function(response, options) {
            ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
        },
        success: function(response, options) {
            var json = response.responseText;
            var obj = parseJsonResult(json);

            if (obj == null || !obj.Success) {
                showMessage("错误！", "保存出现错误！请查看详细原因。", obj.Message);
            }
            else {
                var ids = "";
                for (var i = 0, len = obj.data.length; i < len; i++) {
                    if (i == 0)
                        ids = obj.data[i].UserID + ',';
                    else
                        ids = ids + "," + obj.data[i].UserID;
                }
                ShowOrganUserWin(ids, RoleIDs, '角色用户分配');
            }
        }
    });
}

var GridToolUserBar = new Ext.Panel({
    labelAlign: 'top',
    frame: true,
    //bodyStyle: 'border-bottom:0;',// padding:2 2 2 2;background:#E5E2EE;
    width: "100%",
    html: '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td width="66" align="right" height="26">真实姓名：</td><td align="left" style="width:266px;"><table border="0" cellspacing="0" cellpadding="0"><tr><td width="79" align="left"><input type="text" class="input_l95p_style" style="width: 140;" id="txtChTrueName"></td><td><input name="chStatus" type="radio" value="1" checked="true" />可分配<input name="chStatus" type="radio" value="0" />已分配</td></tr></table></td><td align="left"><input name="button" type="button" class="btn_general_style" id="btnSearchAll" onclick="LoadSearch();" value="查 询" /></td></tr></table>'
});
//创建一个HttpProxy
var fromHttpProxy = new Ext.data.HttpProxy({
    url: strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=SearchNotRoleUsers'
});

//创建一个JsonReader
var fromRecord = new Ext.data.JsonReader({
    root: 'data',
    fields: [
                  { name: 'UserID' },               //人员编码
                  {name: 'TrueName'}              //人员名称
               ]
});
// 定义选择人员数据源
fromStoreUser = new Ext.data.Store({
    proxy: fromHttpProxy,
    reader: fromRecord,
    remoteSort: true
});
//创建一个HttpProxy,已选择人员
var toHttpProxy = new Ext.data.HttpProxy({
    url: strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=SearchRoleUsers'
});
//创建一个JsonReader，已选择人员
var toRecord = new Ext.data.JsonReader({
    root: 'data',
    fields: [
                  { name: 'UserID' },               //人员编码
                  {name: 'TrueName'}              //人员名称
               ]
});
// 定义已选择人员数据源
toStoreUser = new Ext.data.Store({
    proxy: toHttpProxy,
    reader: toRecord,
    remoteSort: true
});
//定义一个Form,角色用户分配
roleForm = new Ext.form.FormPanel({
    width: 480,
    border: false,
    layout: 'fit',
    bodyStyle: 'padding:10px;',
    items: [{
        xtype: "itemselector",
        name: "itemselector",
        dataFields: ["UserID", "TrueName"],
        valueField: "UserID",
        displayField: "TrueName",
        imagePath: strPath + "extjs/multiselect/images/",
        toLegend: "已分配人员",
        fromLegend: "可分配人员",
        toStore: toStoreUser,
        fromStore: fromStoreUser
}],
        tbar: GridToolUserBar,
        buttons: [{
            text: '确定',
            handler: function() {
                if (roleForm.getForm().isValid()) {
                    UpdateUserRole(RoleID);
                }
            }
        },
        {
            text: '关闭',
            handler: function() {
                if (roleForm.getForm().isValid()) {
                    roleDistributionWindow.hide();
                }
            }
}]
        });

        //定义一个窗体,角色用户分配
        roleDistributionWindow = new Ext.Window({
            title: '用户角色分配',
            width: 466,
            height: 438,
            layout: 'fit',
            plain: true,
            bodyStyle: 'padding:10px;',
            buttonAlign: 'center',
            items: roleForm
        });
        // 设置角色用户
        function SetRoleUser(RoleID) {
            roleDistributionWindow.show();
            setValue('txtChTrueName', '');
            fromStoreUser.load({ params: { RoleID: RoleID} });
            toStoreUser.load({ params: { RoleID: RoleID} });
        }
        // 查询事件
        function LoadSearch() {
            var Status = '';
            var obj = document.getElementsByName("chStatus");
            for (i = 0; i < obj.length; i++) {
                if (obj[i].checked) {
                    Status = obj[i].value;
                }
            }
            var TrueName = Ext.get("txtChTrueName").dom.value;
            if (Status == '1') {
                fromStoreUser.load({ params: { RoleID: RoleID, TrueName: TrueName} });
                toStoreUser.load({ params: { RoleID: RoleID} });
            }
            else if (Status == '0') {
                toStoreUser.load({ params: { RoleID: RoleID, TrueName: TrueName} });
                fromStoreUser.load({ params: { RoleID: RoleID} });
            }
        }
        // 更新角色用户
        function UpdateUserRole(RoleID, UserIDs) {
            // 获取选中的ID
            var strUrl = strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SetUserRole';
            Ext.Ajax.request({
                url: strUrl,
                method: 'POST',
                params: {
                    RoleID: RoleID,
                    UserIDs: UserIDs
                },
                failure: function(response, options) {
                    ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                },
                success: function(response, options) {
                    var json = response.responseText;
                    var obj = parseJsonResult(json);

                    if (!obj.Success) {
                        showMessage("错误！", "设置用户状态出现错误！请查看详细原因。", obj.Message);
                    }
                    /*
                    else
                    {
                    roleDistributionWindow.hide();
                    }
                    */
                }
            });
        }

        // 设置角色功能
        function SetRoleAction(RoleID) {
            //创建一个HttpProxy
            var fromAcHttpProxy = new Ext.data.HttpProxy({
                url: strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=SearchNotRoleAction&RoleID=' + RoleID
            });

            //创建一个JsonReader
            var fromAcRecord = new Ext.data.JsonReader({
                root: 'data',
                fields: [
                  { name: 'ActionID' },               //功能编码
                  {name: 'ActionName'}              //功能名称
               ]
            });
            // 定义选择人员数据源
            var fromAcStore = new Ext.data.Store({
                proxy: fromAcHttpProxy,
                reader: fromAcRecord,
                remoteSort: true
            });
            //创建一个HttpProxy,已选择人员
            var toAcHttpProxy = new Ext.data.HttpProxy({
                url: strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=SearchRoleAction&RoleID=' + RoleID
            });
            //创建一个JsonReader，已选择人员
            var toAcRecord = new Ext.data.JsonReader({
                root: 'data',
                fields: [
                  { name: 'ActionID' },               // 功能编码
                  {name: 'ActionName'}              // 功能名称
               ]
            });
            // 定义已选择人员数据源
            var toAcStore = new Ext.data.Store({
                proxy: toAcHttpProxy,
                reader: toAcRecord,
                remoteSort: true
            });
            //定义一个Form,角色用户分配
            RoleActionForm = new Ext.form.FormPanel({
                width: 480,
                border: false,
                layout: 'fit',
                bodyStyle: 'padding:10px;',
                items: [{
                    xtype: "itemselector",
                    name: "itemselector",
                    dataFields: ["ActionID", "ActionName"],
                    valueField: "ActionID",
                    displayField: "ActionName",
                    imagePath: strPath + "extjs/multiselect/images/",
                    toLegend: "已分配功能",
                    fromLegend: "可分配功能",
                    toStore: toAcStore,
                    fromStore: fromAcStore
}],
                    buttons: [{
                        text: '确定',
                        handler: function() {
                            if (RoleActionForm.getForm().isValid()) {
                                // UpdateRoleAction(RoleID);
                            }
                        }
                    },
        {
            text: '关闭',
            handler: function() {
                if (RoleActionForm.getForm().isValid()) {
                    RoleActionWindow.hide();
                }
            }
}]
                });

                //定义一个窗体,角色用户分配
                RoleActionWindow = new Ext.Window({
                    title: '用户功能分配',
                    width: 480,
                    height: 400,
                    layout: 'fit',
                    plain: true,
                    bodyStyle: 'padding:10px;',
                    buttonAlign: 'center',
                    items: RoleActionForm
                });
                RoleActionWindow.show();
                fromAcStore.load();
                toAcStore.load();
            }
            // 设置角色功能
            function UpdateRoleAction(RoleID, MenuIDs) {
                // 获取选中的ID
                // var ActionIDs = RoleActionForm.getForm().getValues().itemselector;
                var strUrl = strPath + 'GGFW/BaseInfo/FoothillMenuCommand.fwf?Method=SetMenuRole';
                Ext.Ajax.request({
                    url: strUrl,
                    method: 'POST',
                    params: {
                        RoleID: RoleID,
                        MenuIDs: MenuIDs
                    },
                    failure: function(response, options) {
                        ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                    },
                    success: function(response, options) {
                        var json = response.responseText;
                        var obj = parseJsonResult(json);

                        if (!obj.Success) {
                            showMessage("错误！", "设置用户状态出现错误！请查看详细原因。", obj.Message);
                        }
                        /*else
                        {
                        RoleActionWindow.hide();
                        }
                        */
                    }
                });
            }
            // 新增角色窗体
            function ShowRoleWin() {
                // 清除角色绑定的信息
                CleanRoleInfo();
                // 打开窗体
                isEdit = false;
                controlShow('divRoleInfo');
                winOrganization.show();
            }
            // 新增、编辑角色的方法
            function AddRole() {
                var myMask = new Ext.LoadMask(Ext.getBody(), {
                    msg: "正在加载数据..."
                });
                myMask.show();
                // 获取参数
                var RoleName = Ext.get("txtRoleName").dom.value;
                var RoleDesc = Ext.get("txtRoleDesc").dom.value;
                var Remark = Ext.get("txtRemark").dom.value;

                // 验证必填项
                var msg = "";
                var strLen = "";
                if (RoleName.trim() == "") msg += "角色名称 ";
                if (GetStrLength(RoleName) > 30) strLen += "角色名称 ";
                if (GetStrLength(RoleDesc) > 50) strLen += "角色说明 ";
                if (GetStrLength(Remark) > 50) strLen += "备注 ";

                if (msg != "" || strLen != "") {
                    myMask.hide();
                    Ext.MessageBox.alert("&nbsp;提示", (msg == "" ? "" : (msg + "不能为空！")) + (strLen == "" ? "" : ("<br/>" + strLen + "输入字符过长!")));

                    return;
                }
                var strUrl = strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=AddFoothillRoleData';
                if (isEdit) strUrl = strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=UpdateFoothillRoleData';
                Ext.Ajax.request({
                    url: strUrl,
                    method: 'POST',
                    params: {
                        // 传递相关参数
                        RoleID: RoleID,
                        RoleName: RoleName,
                        RoleDesc: RoleDesc,
                        Remark: Remark
                    },
                    failure: function(response, options) {
                        myMask.hide();
                        ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                    },
                    success: function(response, options) {
                        myMask.hide();
                        var json = response.responseText;
                        var obj = parseJsonResult(json);

                        if (!obj.Success) {
                            showMessage("错误！", "保存数据出错！", obj.Message);
                        }
                        else {
                            // 关闭窗体并刷新Grid
                            controlShow('divRoleInfo');
                            winOrganization.hide();
                            doSearchRole(false);
                        }
                    }
                });
            }
            // 删除角色的方法
            function DelRole() {
                // 获取要删除的ID
                var strID = getSelectID(gridRole, 'RoleID');
                if (strID == '' || strID == null) {
                    Ext.MessageBox.alert("提示", "请选择数据！"); return;
                }
                // 询问并执行
                Ext.MessageBox.confirm("询问", '确认要删除选中的角色吗？删除后将不可恢复！', function(btn) {
                    if (btn == "yes") {
                        var strUrl = strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=DeleteFoothillRole';
                        Ext.Ajax.request({
                            url: strUrl,
                            method: 'POST',
                            params: {
                                RoleIDs: strID
                            },
                            failure: function(response, options) {
                                ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                            },
                            success: function(response, options) {
                                var json = response.responseText;
                                var obj = parseJsonResult(json);

                                if (!obj.Success) {
                                    showMessage("错误！", "删除角色出现错误！请查看详细原因。", obj.Message);
                                }
                                else {
                                    // 删除成功后重新刷新Grid
                                    doSearchRole(false);
                                }
                            }
                        });
                    }
                });
            }
            // 获取角色信息
            function GetRoleInfo(ID) {
                if (ID == null) return;
                // 清除角色绑定的信息
                CleanRoleInfo();
                RoleID = ID;
                isEdit = true;
                // 打开窗体
                controlShow('divRoleInfo');
                winOrganization.show();
                // 设置空间的状态
                Ext.get("txtRoleName").dom.disabled = true;
                // 查询方法，得到单个角色信息。
                var strUrls = strPath + 'GGFW/BaseInfo/FoothillRoleCmd.fwf?Method=GetFoothillRole&RoleID=' + ID;
                Ext.Ajax.request({
                    url: strUrls,
                    method: 'POST',
                    failure: function(response, options) {
                        ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                    },
                    success: function(response, options) {
                        // 绑定值
                        var json = response.responseText;
                        var obj = parseJsonResult(json);

                        if (obj != null) {
                            if (!obj.Success) {
                                showMessage("错误！", "读取数据出错！", obj.Message);
                            }
                            else if (obj.data[0] != null) {
                                // 绑定角色信息
                                Ext.get("txtRoleName").dom.value = SiftNullAndEmpty(obj.data[0].RoleName);
                                Ext.get("txtRoleDesc").dom.value = SiftNullAndEmpty(obj.data[0].RoleDesc);
                                Ext.get("txtRemark").dom.value = SiftNullAndEmpty(obj.data[0].Remark);
                            }
                        }
                        else {
                            showMessage("错误！", "读取数据出错！");
                        }
                    }
                });
            }
            // 清除角色绑定的信息
            function CleanRoleInfo() {
                setValue('txtRoleName', '');
                setValue('txtRoleDesc', '');
                setValue('txtRemark', '');
                Ext.get("txtRoleName").dom.disabled = false;
            }
            // 查询角色并刷新Grid
            function doSearchRole(isPage) {
                // 获取要查询的参数
                var RoleName = Ext.get("txtChRoleName").dom.value;
                if (storeRole == null) return;
                // 执行Grid重新刷新的方法
                if (isPage) storeRole.load({ params: { start: 0, limit: pageSize, RoleName: RoleName} });
                else storeRole.load({ params: { start: (gridRole.getBottomToolbar().getPageData().activePage - 1) * pageSize, limit: pageSize, RoleName: RoleName} });
            }
